﻿using System;

namespace Kay.BaseLibrary.Helpers
{
    /// <summary>
    /// 枚举帮助器
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举的 EnumKey 特性
        /// </summary>
        /// <param name="value">需要获取的枚举值</param>
        /// <returns>获取到的值</returns>
        public static string GetKey(Enum value)
        {
            var field = value.GetType().GetField(value.ToString());

            var attribute
                = Attribute.GetCustomAttribute(field, typeof(EnumKeyAttribute))
                    as EnumKeyAttribute;

            return attribute == null ? value.ToString() : attribute.Description;
        }

        /// <summary>
        /// 通过 EnumKey 特性值获取枚举的值
        /// </summary>
        /// <param name="key">特性值</param>
        /// <typeparam name="T">枚举类型</typeparam>
        /// <returns>key 特性对应的枚举值</returns>
        /// <exception cref="InvalidOperationException">类型不是枚举类型</exception>
        /// <exception cref="ArgumentException">没有找到对应的枚举值</exception>
        public static T GetEnumByKey<T>(string key) where T : struct
        {
            var type = typeof(T);
            if (!type.IsEnum)
            {
                throw new InvalidOperationException();
            }
            foreach (var field in type.GetFields())
            {
                var attribute = Attribute.GetCustomAttribute(field,
                    typeof(EnumKeyAttribute)) as EnumKeyAttribute;
                if (attribute != null)
                {
                    if (attribute.Description == key)
                        return (T)field.GetValue(null);
                }
                else
                {
                    if (field.Name == key)
                        return (T)field.GetValue(null);
                }
            }
            throw new ArgumentException("没有发现", nameof(key));
        }
    }
}
